var ip = '';
const db = uniCloud.database();
var _appId = '';
var _wxPayKey = '';
var _wxPayMchId = '';
var isMiniApp = '';
var _notifyUrl = '';
module.exports = {
  /**
   * 微信h5支付
   * @url admin/kong/sys/add 前端调用的url参数地址
   * data 请求参数 说明
   * res 返回参数说明
   * @param {Number} code 错误码，0表示成功
   * @param {String} msg 详细信息
   */
  main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk , db, _ } = util;
		let { uid,dbName } = data;
		let res = { code : 0, msg : 'ok' };
    // 业务逻辑开始-----------------------------------------------------------
		const appIds = await db.collection('wx_config').where({
			'key': 'wxIdH5'
		}).get()
		const wxPayKey = await db.collection('wx_config').where({
			'key': 'wxPayKey'
		}).get()
		const wxPayMchId = await db.collection('wx_config').where({
			'key': 'wxPayMchId'
		}).get()
		if (appIds.data.length === 0 || wxPayKey.data.length === 0 || wxPayMchId.data.length === 0) {
			return '未配置系统参数'
		}
		_appId = appIds.data[0].val
		_wxPayMchId = wxPayMchId.data[0].val
		_wxPayKey = wxPayKey.data[0].val
		
		var Payment = require('wechat-pay').Payment;
		var initConfig = {
			partnerKey: _wxPayKey,
			appId: _appId,
			mchId: _wxPayMchId,
			notifyUrl: "https://wwww.baidu.com",
			// pfx: fs.readFileSync("<location-of-your-apiclient-cert.p12>")
		};
		var payment = new Payment(initConfig);
		console.log(data,'1111111111111111')
		var order = {
			body: data.title,
			// attach: event.attach,
			out_trade_no: data.order_id,
			total_fee: Number((Number(data.money) * 100).toFixed(2)),
			spbill_create_ip: originalParam.context.CLIENTIP,
			openid: data.openid,
			trade_type: 'JSAPI'
		};
		
		function getBrandWCPayRequestParams() {
			return new Promise((res, rej) => {
				payment.getBrandWCPayRequestParams(order, function(err, payargs) {
					if (err) {
						rej(err)
						return
					}
					res(payargs)
				});
			})
		
		}
		
	var data1 = await getBrandWCPayRequestParams()
	res.data = data1
    // 业务逻辑结束-----------------------------------------------------------
    return res;
  }
}
